package com.way.capture.utils.glide;

import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Key;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.way.capture.R;

import java.io.File;

public class GlideHelper {

    public static void loadResourceGif(String path, @NonNull ImageView image) {
        RequestOptions options = new RequestOptions().fitCenter();

        Glide.with(image.getContext().getApplicationContext())
                .asGif()
                .load(path)
                .apply(options)
                .into(image);
    }

    public static void loadResourceBitmap(String path, @NonNull ImageView image) {
        Glide.with(image.getContext().getApplicationContext())
                .asBitmap()
                .load(path)
                .apply(getGlideRequestOptions(path))
                .into(image);
    }

    public static void loadResourceBitmap(String path, @NonNull ImageView image,
                                          RequestListener<Bitmap> requestListener) {
        Glide.with(image.getContext().getApplicationContext())
                .asBitmap()
                .load(path)
                .listener(requestListener)
                .apply(getGlideRequestOptions(path))
                .into(image);
    }

    public static void loadResourceBitmapCenterCrop(String path, @NonNull ImageView image) {
        RequestOptions options = new RequestOptions().centerCrop();
        Glide.with(image.getContext().getApplicationContext())
                .asBitmap()
                .load(path)
                .apply(options)
                .into(image);
    }


    public static Key getGlideSignature(String path) {
        File file = new File(path);
        String lastModified = String.valueOf(file.lastModified());
        return new ObjectKey(lastModified);
    }

    public static RequestOptions getGlideRequestOptions(String path) {
        return new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .placeholder(R.color.image_bg)
                .signature(getGlideSignature(path));
    }
}
